﻿using Interfaces.Model;
using LiveCharts;
using LiveCharts.Wpf;
using Microsoft.Extensions.DependencyInjection;
using Models;
using Newtonsoft.Json;
using Services;
using System.Windows;
using System.Windows.Input;
using Utils;
using WorkPieceDataCapture.ViewModels;

namespace ViewModels
{
    public class vm_Chart_NG : vm_Base
    {
        #region 全局变量与枚举
        private IServiceProvider _serviceProvider;
        WorkPieceDataCaptureRespository respository;
        private SeriesCollection _pieData;
        public SeriesCollection PieData  //饼图的数据源
        {
            get => _pieData;
            set
            {
                _pieData = value;
                OnPropertyChanged(nameof(PieData));
            }
        }
        private model_SearchCondition _conditions;
        public model_SearchCondition conditions
        {
            get
            {
                return _conditions;
            }
            set
            {
                _conditions = value;
                OnPropertyChanged(nameof(conditions));
            }
        }//查询条件
        private string _Yield;
        public string Yield    //统计产量
        {
            get
            {
                return _Yield;

            }
            set
            {
                _Yield = value;
                OnPropertyChanged(nameof(Yield));
            }
        }

        #endregion
        #region 事件注册
        public ICommand doSummaryCommand { get; set; }   //执行查询事件
        public ICommand doExportCommand { get; set; }  //执行导出明细数据的事件
        #endregion
        #region 构造与析构函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public vm_Chart_NG(IServiceProvider serviceProvider)
        {
            this._serviceProvider = serviceProvider;
            this.respository = new WorkPieceDataCaptureRespository(this._serviceProvider);
            doSummaryCommand = new RelayCommand(doSummary);   //点击查询按钮的事件注册
            doExportCommand = new RelayCommand(doExport);   //执行导出列表的事件注册
            initialize();
        }
        /// <summary>
        /// 析构函数
        /// </summary>
        ~vm_Chart_NG()
        {

        }
        #endregion
        #region 事件
        /// <summary>
        /// 类的初始化
        /// </summary>
        /// <returns></returns>
        public IFuncResult<string> initialize()
        {
            var result = new FuncResult<string>();
            try
            {
                this.conditions = new model_SearchCondition();
                this.conditions.dDate_End = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
                this.conditions.dDate_Begin = this.conditions.dDate_End.Value.AddDays(-7);
                result.bSuccess = true;
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }
        /// <summary>
        /// 执行数据查询
        /// </summary>
        /// <param name="parameter"></param>
        private void doSummary(object parameter)
        {
            try
            {
                var context = this._serviceProvider.GetService<AppDbContext>();
                if (context != null)
                {
                    if (conditions.dDate_Begin > conditions.dDate_End)
                    {
                        MessageBox.Show("开始日期不能大于结束日期！");
                        return;
                    }
                    var list_Final = new List<tb_WorkPieceDataCapture_Realtime>();    //存放最终结果
                    var list_FinalJson = new List<string>();    //存放不同实体类但是相同结构的数据的json
                    #region 如果查询的年月区间包含一个月以内的数据，则需要从实时表里查询数据
                    var nowYearMonth = DateTime.Now.ToString("yyyyMM");
                    if (int.Parse(nowYearMonth) >= int.Parse(conditions.dDate_Begin.Value.ToString("yyyyMM"))
                        && (int.Parse(nowYearMonth) <= int.Parse(conditions.dDate_End.Value.ToString("yyyyMM"))))
                    {
                        var result = this.respository.SearchDataFromRealTimeTable(conditions, context.tb_workpiecedatacapture_realtime);
                        if (result.bSuccess)
                        {
                            if (result.obj_Return.Count > 0)
                            {
                                list_Final.AddRange(result.obj_Return);
                            }
                        }
                        else
                        {
                            MessageBox.Show("从实时数据表中获取数据时出现错误！" + result.strMsg);
                            return;
                        }
                    }
                    #endregion
                    #region 根据起始日期到结束日期的年份确认用到的历史表并执行查询
                    for (var i = conditions.dDate_Begin.Value.Year; i <= conditions.dDate_End.Value.Year; i++)
                    {
                        // 使用新的动态查询方法
                        var yearResult = respository.SearchDataFromHistoryTableByYear(i, conditions);
                        if (yearResult.bSuccess)
                        {
                            yearResult.obj_Return.ForEach(ee =>
                            {
                                list_FinalJson.Add(JsonConvert.SerializeObject(ee));
                            });
                        }
                        else
                        {
                            MessageBox.Show($"从{i}年历史表中获取数据时出现错误！" + yearResult.strMsg);
                            return;
                        }
                    }
                    #endregion
                    list_FinalJson.ForEach(ee =>
                    {
                        list_Final.Add(JsonConvert.DeserializeObject<tb_WorkPieceDataCapture_Realtime>(ee));
                    });
                    var total = list_Final.Count;
                    if (total == 0)
                    {
                        MessageBox.Show("当天没有产量");
                        return;
                    }
                    var OK = list_Final.Where(ee => ee.ZC_Result == "OK").Count();
                    var NG = list_Final.Where(ee => ee.ZC_Result == "NG").Count();
                    var OKPercent = MathMethods.CalculatePercentage(OK, total);
                    var NGPercent = MathMethods.CalculatePercentage(NG, total);
                    this.Yield = string.Format("总产量：{0}；OK：{1}；占比：{2}；NG：{3}；占比：{4}；", total, OK, OKPercent, NG, NGPercent);
                    PieData = new SeriesCollection()
                    {
                        new PieSeries{Title = "分零件：一次圈("+list_Final.Where(ee=>ee.FLJ_YCQ_Result=="NG").Count().ToString()+")" ,Values = new ChartValues<double> { list_Final.Where(ee=>ee.FLJ_YCQ_Result=="NG").Count() }, DataLabels = true},
                        new PieSeries{Title = "分零件：隔离环("+list_Final.Where(ee=>ee.FLJ_GLH_Result=="NG").Count().ToString()+")" ,Values = new ChartValues<double> { list_Final.Where(ee=>ee.FLJ_GLH_Result=="NG").Count() }, DataLabels = true},
                        new PieSeries{Title = "分零件：二次圈("+list_Final.Where(ee=>ee.FLJ_ECQ_Result=="NG").Count().ToString()+")" ,Values = new ChartValues<double> { list_Final.Where(ee=>ee.FLJ_ECQ_Result=="NG").Count() }, DataLabels = true},
                        new PieSeries{Title = "分零件：安全环("+list_Final.Where(ee=>ee.FLJ_KZH_Result=="NG").Count().ToString()+")" ,Values = new ChartValues<double> { list_Final.Where(ee=>ee.FLJ_KZH_Result=="NG").Count() }, DataLabels = true},
                        new PieSeries{Title = "分零件：内密("+list_Final.Where(ee=>ee.FLJ_NM_Result=="NG").Count().ToString()+")" ,Values = new ChartValues<double> { list_Final.Where(ee=>ee.FLJ_NM_Result == "NG").Count() }, DataLabels = true},
                        new PieSeries{Title = "分零件：锁扣("+list_Final.Where(ee=>ee.FLJ_SK_Result=="NG").Count().ToString()+")" ,Values = new ChartValues<double> { list_Final.Where(ee=>ee.FLJ_SK_Result=="NG").Count() }, DataLabels = true},
                        new PieSeries{Title = "分零件：外密("+list_Final.Where(ee=>ee.FLJ_WM_Result=="NG").Count().ToString()+")" ,Values = new ChartValues<double> { list_Final.Where(ee=>ee.FLJ_WM_Result=="NG").Count() }, DataLabels = true},
                        new PieSeries{Title = "检测仪：内密气密("+list_Final.Where(ee=>ee.JCY_QM_Result=="NG").Count().ToString()+")" ,Values = new ChartValues<double> { list_Final.Where(ee=>ee.JCY_QM_Result=="NG").Count() }, DataLabels = true},
                        new PieSeries{Title = "检测仪：壳体气密("+list_Final.Where(ee=>ee.JCY_KTQM_Result=="NG").Count().ToString()+")" ,Values = new ChartValues<double> { list_Final.Where(ee=>ee.JCY_KTQM_Result=="NG").Count() }, DataLabels = true},
                        new PieSeries{Title = "打码扫码检测("+list_Final.Where(ee=>ee.ZC_DM_Result=="NG").Count().ToString()+")" ,Values = new ChartValues<double> { list_Final.Where(ee=>ee.ZC_DM_Result == "NG").Count() }, DataLabels = true}
                    };
                }
                else
                {
                    MessageBox.Show("当前无法连接到数据库，请重试一次");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行查询操作发生异常！\n" + ex.Message);
            }
        }
        /// <summary>
        /// 执行导出列表数据
        /// </summary>
        /// <param name="parameter"></param>
        private void doExport(object parameter)
        {

        }
        #endregion
    }
}
